# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.

# import logging
# _logger = logging.getLogger(__name__)

from odoo.addons.iot_mqtt.controllers.main import IotMqttInterface

from odoo import models, fields, api, _


class IotMqttModel(models.AbstractModel):
    _inherit = "iot.mqtt.interface"

    @api.model
    def on_message(self, router_code, method, *args, **kwargs):
        print('IotMqttModel, on_message', self._name, router_code, method, args, kwargs)
        
        if method == 'ack':
            self.on_message_ack(router_code, *args, **kwargs)

        else:
            self._on_message_check( router_code, method, *args, **kwargs )


    @api.model
    def on_message_ack(self, router_code, origin_menthod, *args, **kwargs):
        print('on_message_ack: ', self._name,router_code, origin_menthod, args, kwargs)
        self._on_message_check( router_code, origin_menthod + '_ack', *args, **kwargs )

    @api.model
    def _on_message_check(self, router_code, method, *args, **kwargs):
        print('_on_message_check: ',self._name, router_code, method, args, kwargs)
        model, code = args and args or ['router', router_code]
        self._on_message( model, method, code, **kwargs)

    
    @api.model
    def _on_message(self, model, method, code, **kwargs):
        print('_on_message gateway: ', self._name, model, code, kwargs)

        if model not in ['router', 'node']:
            print( 'error',  'model not in router, node') 
            return 

        obj = {'router': self,'node': self.env['iot.device'] }[model]
        getattr(obj, 'on_message_' + method)( code, **kwargs)

    
